import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
import './TagSelector.less'
import { Icon, Input, Tag } from 'antd'
import { removeListener } from 'process'
interface ITagSelectorProps {
    childrenValues:Array<{name:string,value:any}>
    values:Array<{name:string,value:string}>
    children?: React.ReactNode,
    onDropdownVisibleChange?: (visible:boolean) => void,
    onChange?: (value:Array<string>) => void
}
const tagColors =['green','blue','cyan','red','orange','purple']
function TagSelector( props:ITagSelectorProps ) {
    const [tags, setTags] = useState<Array<{name:string,value:string}>>([])
    const [showInput, setShowInput] = useState<boolean>(false)
    const [visible,setVisible] = useState<boolean>(true)
    const refInput = useRef(null)
    const refContainer = useRef(null)
    const refSelector = useRef(null)
    const values = useRef(props.values)
    useEffect(()=>{
      console.log("tags....",props.values)
      setTags(props.values)
      values.current = props.values
    },[props.values])
   
    
    useEffect(()=>{
      if( showInput ) refInput.current.focus()
    }, [showInput])
    useEffect(()=>{
      document.body.addEventListener('mouseup',handleCheckVisible)
      return ()=>document.body.removeEventListener('mouseup',handleCheckVisible)
    },[])
    const handleCheckVisible = (e:any) => {
      if( !refContainer.current ) return
      if( refContainer.current.contains(e.target) ) return
      setVisible(false)
      props.onDropdownVisibleChange && props.onDropdownVisibleChange(false)
    }
    const handleInputChange = (e:any) => {
        
    }
    const handleInputConfirm = () => {
        const inputValue = refInput.current.state.value;
        if (inputValue) {
          const newTags = [...tags, { name: inputValue, value: inputValue }]
          props.onChange && props.onChange(newTags.map(item=>item.value))
          setTags(newTags);
        }

        setShowInput(false)
    }
    const handleClose = (removedTag:any) => {
        const newTags = tags.filter(tag => tag !== removedTag);
        props.onChange && props.onChange(newTags.map(item=>item.value))
        setTags(newTags);
    }
    useLayoutEffect(() => {
      setTimeout(()=>{
        const container = refContainer.current;
        //debugger
        if (!container) return;
    
        const containerRect = container.getBoundingClientRect();
        const bodyRect = document.body.getBoundingClientRect();
        const offset = 60
        if (containerRect.right + offset  > bodyRect.right) {
          container.style.left = `${bodyRect.right - containerRect.right - offset}px`;
        }
      },0)
      
    }, [props.childrenValues]);
    const tagLists = [].concat(tags.concat())
    props.childrenValues.forEach((item)=>{
      if( !tagLists.find(tag=>tag.name == item.name) ){
        tagLists.push(item)
      }
    })

    return (
        <div className="tag-selector" ref={refSelector}>

            <div className="tag-selector-input">
               <Icon type="edit" style={{fontSize:'12px'}} />
            </div>
            <div className="tag-selector-content" ref={refContainer}>
                { tagLists.map((item,index)=>{
                  const current = tags.find(tag=>tag.name == item.name)
                  
                  return <Tag  color={ current?'blue':''}  key={item.value}
                      onClose={e => {
                        e.preventDefault();
                        handleClose(item);
                      }}
                      onClick={(e)=>{
                        if( current ){
                          values.current = values.current.filter(tag=>tag.name!= item.name)
                        }else{
                          values.current = [...values.current,{ name:item.name,value:item.name }]
                        }
                        console.log('tags',values.current)
                        props.onChange && props.onChange(values.current.map(item=>item.value))
                        setTags(values.current)

                      }}
                    >{ item.name } </Tag>
                })
                }
                { 
                  showInput && <Input maxLength={10} ref={refInput} size='small' className='tag-selector-input-tag'
                  onChange={handleInputChange}
                  onBlur={handleInputConfirm}
                  onPressEnter={handleInputConfirm}
                  >
                 </Input>
                }
                {
                  !showInput &&  (
                    <Tag onClick={(e)=>setShowInput(true)} style={{ background: '#fff', borderStyle: 'dashed' }}>
                      <Icon type="plus" /> 新标签
                    </Tag>
                  )
                }
            </div>
        </div>
    )
}

export default TagSelector
